{% extends "admin42/platformmgr/base.html" %}
{% load admin_utils %}
{% block main_content %}
<div id="platform-plans-list" style="width: 100%;" class="p20">
    <bk-button :theme="'primary'" :title="'创建服务方案'" class="mr10" @click="handleCreate">
        创建服务方案
    </bk-button>
    <bk-table :data="data" :cell-class-name="cellStyleCallback" style="margin-top: 20px;">
        <bk-table-column width="45" align="center">
            <template slot-scope="props">
                <img :src="props.row.logo" width="30"/>
            </template>
        </bk-table-column>
        <bk-table-column label="方案名称" prop="name">
        </bk-table-column>
        <bk-table-column label="方案配置" prop="config" width="300">
            <template slot-scope="props">
                <json-pretty :data="props.row.config" show-length highlight-mouseover-node :deep="2"></json-pretty>
            </template>
        </bk-table-column>
        <bk-table-column label="所属服务" prop="service_name"></bk-table-column>
        <bk-table-column label="可用区" prop="region"></bk-table-column>
        <bk-table-column label="是否启用" prop="is_active">
            <template slot-scope="props">
                <span v-if="props.row.is_active">是</span>
                <span v-else>否</span>
            </template>
        </bk-table-column>
        <bk-table-column label="操作">
            <template slot-scope="props">
                <a class="bk-text-button mr10" href="javascript:void(0);" @click="handleEdit(props.row)">编辑</a>
                <bk-button theme="primary" text @click="handleDelete(props.row)" style="color: rgb(234, 54, 54);">删除</bk-button>
            </template>
        </bk-table-column>
    </bk-table>

    <bk-dialog v-model="dialog.visible" header-position="left" width="800" :confirm-fn="submitDialog" @cancel="cancelDialog" :mask-close="false" :fullscreen="dialog.fullscreen">
        <div slot="header">
            $[ dialog.type === 'create'?'添加':(dialog.type === 'edit'?'编辑':'删除') ]服务方案
        </div>
        <bk-form :label-width="120" :model="dialog.form">
            <bk-form-item label="方案名称" :required="true" :desc="'命名约定: no-ha, 仅允许 stag 环境使用; ha, 仅允许 prod 环境使用; 其他名称, 无限制.'">
                <bk-input v-model="dialog.form.name" :disabled="dialog.type === 'delete'"></bk-input>
            </bk-form-item>
            <bk-form-item label="方案简介" :required="true">
                <bk-input v-model="dialog.form.description" :disabled="dialog.type === 'delete'"></bk-input>
            </bk-form-item>
            <bk-form-item label="方案配置" :required="true">
                <json-editor v-model="dialog.form.config" :disabled="dialog.type === 'delete'" :schema="dialog.schema" ref="config-editor"></json-editor>
            </bk-form-item>
            <bk-form-item label="是否可用" :required="true">
                <bk-switcher v-model="dialog.form.is_active" :disabled="dialog.type === 'delete'"></bk-switcher>
            </bk-form-item>
            <bk-form-item label="所属服务" :required="true">
                <bk-select v-model="dialog.form.service_id" :disabled="dialog.type === 'delete'" @change="handleServiceChange">
                    <bk-option v-for="service in services"
                        :key="service.uuid"
                        :id="service.uuid"
                        :name="service.name + '-' + service.region">
                    </bk-option>
                </bk-select>
            </bk-form-item>
            <bk-form-item label="可用区" :required="true" v-if="dialog.service_origin === 'remote'">
                <bk-select v-model="dialog.form.region" :disabled="dialog.type === 'delete'">
                    <bk-option v-for="region in regionList"
                        :key="region.value"
                        :id="region.value"
                        :name="region.text">
                    </bk-option>
                </bk-select>
            </bk-form-item>
            <bk-form-item label="规格定义" v-if="dialog.form.service_id">
                <div>
                    <template v-for="(value, name) in dialog.form.specifications">
                        <bk-tag closable :key="name" @close="removeSpecificationFromService(name)">$[ name ]: $[ value ]</bk-tag>
                    </template>
                    <bk-button icon="plus" size="small" @click="showCreateSpecification" v-if="!specificationDialog.visible"></bk-button>
                    <template v-else>
                        <bk-input v-model="specificationDialog.form.value">
                            <bk-select v-model="specificationDialog.form.key" slot="prepend" style="min-width: 80px;">
                                <bk-option v-for="specDefinition in dialog.specDefinitions"
                                    :key="specDefinition.name"
                                    :id="specDefinition.name"
                                    :name="specDefinition.display_name">
                                </bk-option>
                            </bk-select>
                            <div slot="append" style="min-width: 88px;">
                                <bk-button icon="plus" @click="addSpecificationToService(specificationDialog.form)"></bk-button>
                                <bk-button icon="close-circle-shape" @click="specificationDialog.visible = false"></bk-button>
                            </div>
                        </bk-input>
                    </template>
                </div>
            </bk-form-item>
        </bk-form>
    </bk-dialog>
</div>

{% endblock %}


{% block main_script %}
<script>
const plans = {{ plans | to_json }}
const services = {{ services | to_json }}
const regionList = {{ region_list | to_json }}
const planConfigSchemas = {{ plan_config_schemas | to_json }}


const URLRouter = {
    create: decodeURI("{% url 'admin.plans.create' '${service_id}' %}"),
    list: decodeURI("{% url 'admin.plans.list' %}"),
    detail: decodeURI("{% url 'admin.plans.detail' '${service_id}' '${plan_id}' %}"),
}

document.addEventListener('DOMContentLoaded', () => {
    new Vue({
        el: "#platform-plans-list",
        delimiters: ['$[', ']'],
        mixins: [SubmitMixin],
        data: function () {
            let include_inactive = false
            let market_enabled = undefined
            return {
                data: plans,
                services,
                regionList: regionList,
                advancedFilterForm: {
                    include_inactive,
                    market_enabled,
                },
                dialog: {
                    fullscreen: false,
                    form: {
                        name: '',
                        description: '',
                        config: {

                        },
                        specifications: {},
                        properties: {},
                        service_id: '',
                        is_active: true,
                    },
                    service_origin: '',
                    schema: undefined,
                    row: undefined,
                    specDefinitions: []
                },
                specificationDialog: {
                    form: {},
                    visible: false,
                    type: 'create',
                },
                advancedFilterShow: false
            }
        },
        methods: {
            handleServiceChange: function (service_uuid) {
                this.dialog.schema = planConfigSchemas[service_uuid]
                this.dialog.specDefinitions = services.filter(item=>item.uuid === service_uuid)[0]?.specifications || []
                this.dialog.service_origin = services.filter(item=>item.uuid === service_uuid)[0]?.origin || 'local'
            },
            fillUrlTemplate: function (url_template, {form, row}) {
                return url_template.replace("${plan_id}", row?.uuid).replace("${service_id}", form?.service_id)
            },
            cancelDialog: function () {

            },
            processData: function (data) {
              return new Promise(resolve => {
                  resolve(data)
              })
            },
            submitCallback: function () {
                // 更新列表
                this.$http.get(URLRouter['list']).then(res => {
                    this.data = res
                })
            },
            handleCreate: function () {
                this.dialog.type = "create"
                this.dialog.row = undefined

                this.dialog.form.uuid = undefined
                this.dialog.form.name = undefined
                this.dialog.form.description = undefined
                this.dialog.form.config = {}
                this.dialog.form.specifications = {}
                this.dialog.form.properties = {}
                this.dialog.form.is_active = false
                this.dialog.form.service_id = undefined

                this.dialog.visible = true
            },
            handleEdit: function (row){
                this.dialog.type = "edit"
                this.dialog.row = row

                this.dialog.form = JSON.parse(JSON.stringify(row))

                this.dialog.visible = true
            },
            handleDelete: function (row) {
                this.dialog.type = "delete"
                this.dialog.row = row

                this.dialog.form = JSON.parse(JSON.stringify(row))

                this.dialog.visible = true
            },
            cellStyleCallback: function ({row, column, rowIndex, columnIndex}) {
                if (column.label === "方案配置")
                    return 'json-view'
            },
            // 规格管理
            showCreateSpecification: function () {
                this.specificationDialog.visible = true
                this.specificationDialog.type = 'create'

                this.specificationDialog.form = {}
            },
            addSpecificationToService: function (spec) {
                for (let key in this.dialog.form.specifications) {
                    if (key === spec.key) {
                        return this.$paasMessage({
                        theme: 'error',
                        message: `字段名为 '${spec.key}' 的规格已定义.`
                        })
                    }
                }
                this.dialog.form.specifications[spec.key] = spec.value
                this.specificationDialog.visible = false
            },
            removeSpecificationFromService: function (key) {
                if (this.dialog.form.specifications[key] !== undefined) {
                    this.$delete(this.dialog.form.specifications, key)
                }
            }
        },
    })
})

</script>
{% endblock %}
